package controller

import (
	common2 "agent-list---web-development/list/common"
	"agent-list---web-development/list/model"
	"agent-list---web-development/list/response"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"log"
	"net/http"
)

func Login(c *gin.Context) {
	DB := common2.GetDB()
	UserName := c.PostForm("username")
	Account := c.PostForm("account")
	password := c.PostForm("password")
	var user model.User
	DB.Where("account=? and username=?", Account, UserName).First(&user)
	if user.Id == 0 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户名或账号不正确！")
		return
	}

	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		response.Response(c, http.StatusBadRequest, 400, nil, "密码错误！")
		return
	}

	token, err := common2.ReleaseToken(user)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "系统异常！"})
		log.Printf("token generate error:%v", err)
		return
	}
	response.Success(c, gin.H{"token": token, "user": user}, "登录成功！")
}
